<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
    <title>Document</title>
    <link rel="stylesheet" type="text/css" href="../jquery-easyui-1.5.5.5/themes/default/easyui.css">
    <link rel="stylesheet" type="text/css" href="../jquery-easyui-1.5.5.5/themes/icon.css">
    <script type="text/javascript" src="../jquery-easyui-1.5.5.5/jquery.min.js"></script>
    <script type="text/javascript" src="../jquery-easyui-1.5.5.5/jquery.easyui.min.js"></script>
    <script type="text/javascript" src="../js/jquery.serializejson.min.js"></script>
    <script type="text/javascript" src="../js/jquery.moment.js"></script>
</head>

<body>

    <div class="easyui-panel" style="width:700px;" data-options="fit:true">
        <div class="easyui-layout" data-options="fit:true">
            <div data-options="region:'west'" style="width:170px;padding:10px">
                <ul id="tt" class="easyui-tree">
                   
                </ul>
            </div>

            <div data-options="region:'center'" >
                <table id="dg" style="width:100%;height:100%"></table>
            </div>
        </div>
    </div>
    
    <div id="dlgcomment" class="easyui-dialog" title="数据操作" data-options="closed:true,iconCls:'icon-save',modal:true" style="width:620px;height:600px;padding:10px">
        <table id="dgcomment" data-options="fit:true">

        </table>
    </div>

    <div id="tb" style="padding:2px 5px;"> 
        标题: <input class="easyui-textbox" style="width:300px" id="searchName">
        <a href="#" class="easyui-linkbutton" iconCls="icon-search" id="searchData">搜索</a>
        <a href="#" class="easyui-linkbutton" iconCls="icon-add" id="addData">添加新闻</a>
        <a href="#" class="easyui-linkbutton" iconCls="icon-remove" id="removesData">批量删除</a>
    </div>
    <div id="tbcomment" style="padding:2px 5px;">
        <select class="easyui-combobox" name="state" labelPosition="top" style="width:100px;text-align:center">
            <option value=""  selected>全部</option>
            <option value="1">已通过</option>
            <option value="2">未通过</option> 
        </select>
        <a href="#" class="easyui-linkbutton" iconCls="icon-add" id="checkData">批量通过</a>
        <a href="#" class="easyui-linkbutton" iconCls="icon-remove" id="uncheckData">批量不通过</a>
        <a href="#" class="easyui-linkbutton" iconCls="icon-remove" id="betchData">批量删除</a>
        <a href="#" class="easyui-linkbutton" iconCls="icon-add" id="addcommentData">添加评论</a>
        <input type="hidden" id='commentnews' style="width:100%">
        <input type="hidden" id="commentnewsid" style="width:100%">
    </div>
    <div id="addcomment" class="easyui-dialog" title="添加评论" data-options="closed:true,iconCls:'icon-save',modal:true" style="width:600px;height:400px;padding:10px">
        <form id="ffcomment" method="post">
            <div style="margin-bottom:20px">
                <input class="easyui-textbox" id='commentauthor' name="author" style="width:100%" data-options="label:'评论者:',required:true">
            </div>
            <div style="margin-bottom:20px">
                <input class="easyui-textbox" id="commentcontent" name="content" style="width:100%" data-options="label:'内容:',required:true">
            </div>
            <!-- <div style="margin-bottom:20px">
                <input class="easyui-textbox" name="time" style="width:100%" data-options="label:'内容:',required:true">
            </div>
            <div style="margin-bottom:20px">
                <input class="easyui-textbox" name="pushtime" style="width:100%" data-options="label:'上传时间:',required:true">
            </div> -->
        </form>
        <div style="text-align:center;padding:5px 0">
            <a href="javascript:void(0)" class="easyui-linkbutton" onclick="submitcommentForm()" style="width:80px">提交</a>
            <a href="javascript:void(0)" class="easyui-linkbutton" onclick="clearcommentForm()" style="width:80px">清空</a>
        </div>
    </div>
    <div id="dlg" class="easyui-dialog" title="数据操作" data-options="closed:true,iconCls:'icon-save'" style="width:600px;height:630px;padding:10px">
        <form id="ff" method="post">
            <input type="hidden" name="_id" style="width:100%">
            <div style="margin-bottom:20px">
                <input class="easyui-textbox" name="title" style="width:100%" data-options="label:'标题:',required:true">
            </div>
            <div style="margin-bottom:20px">
                <input class="easyui-textbox" name="subtitle" style="width:100%" data-options="label:'副标题:',required:true">
            </div>
            <div style="margin-bottom:20px">
                <input class="easyui-textbox" name="content" style="width:100%" data-options="label:'内容:',required:true">
            </div>
            
            <div style="margin-bottom:20px">
                <input class="easyui-textbox" name="pushtime" style="width:100%" data-options="label:'上传时间:',required:true">
            </div>
            <div style="margin-bottom:20px">
                <input class="easyui-textbox" name="author" style="width:100%" data-options="label:'作者:',required:true">
            </div>
            <div style="margin-bottom:20px">
                <input class="easyui-textbox" name="reporter" style="width:100%" data-options="label:'记者:',required:true">
            </div>
            <div style="margin-bottom:20px">
                <input class="easyui-textbox" name="source" style="width:100%" data-options="label:'来源:',required:true">
            </div>
            <div style="margin-bottom:20px">
                <input class="easyui-textbox" name="keyword" style="width:100%" data-options="label:'关键字:',required:true">
            </div>
            
        </form>
        <div style="text-align:center;padding:5px 0">
            <a href="javascript:void(0)" class="easyui-linkbutton" onclick="submitForm()" style="width:80px">提交</a>
            <a href="javascript:void(0)" class="easyui-linkbutton" onclick="clearForm()" style="width:80px">清空</a>
        </div>
    </div>

    <div id="nodeMenu" class="easyui-menu" style="width: 120px;">
        <div iconcls="icon-add" id='BtnAddNode'>添加子节点</div>
        <div iconcls="icon-add" id='BtnAddBroNode'>添加同级节点</div>
        <div iconcls="icon-remove" id='BtnDeleteNode'>删除节点</div>
        <div iconcls="icon-edit" id='BtnEditNode'>编辑节点</div>
    </div>
</body>

</html>

<script>
    var host='http://10.31.156.62:3000'

    var nodeSelected;//左键点击选中的分类节点
    var nodeParent;//左键点击选中的分类节点的父节点
    var nodeChecked;//右键点击选中的分类节点
    var nodeCheckedParent;//右键点击选中的分类节点的父节点
    var beforeEditText;//节点编辑前的文本
    var commentid;//点击查看评论保存的id

    function submitForm() {
        $('#ff').form('submit', {
            onSubmit: function () {
                if ($(this).form('enableValidation').form('validate')) {

                    var formData = $("#ff").serializeJSON();
                    if (formData._id.length > 0) {
                        // 修改操作
                        $.ajax({
                            url: `${host}/news/data/${formData._id}`,
                            type: 'put',
                            data: formData
                        }).then(res => {
                            $('#dlg').dialog('close')
                            $('#dg').datagrid('reload');
                        })
                    } else {
                        // 新增操作
                        delete formData._id;
                        var parentcate=nodeParent?nodeParent.text:''
                        $.ajax({
                            url: `${host}/news/data`,
                            type: 'post',
                            data: Object.assign(formData,{
                                belong:nodeSelected.path+nodeSelected._id,
                                parentcate:parentcate,
                                nowcate:nodeSelected.text,
                                commentnum:0
                            })
                        }).then(res => {
                            $('#dlg').dialog('close')
                            $('#dg').datagrid('reload');
                        })
                    }

                }
            }
        });
    }
    function submitcommentForm() {
        $('#ffcomment').form('submit', {
            onSubmit: function () {
                if ($(this).form('enableValidation').form('validate')) {
                    var formData = $("#ffcomment").serializeJSON();
                    formData['time']=new Date().toLocaleDateString();
                    formData['state']='不通过';
                    formData['news']=$('#commentnews').val();
                    formData['newsid']=$('#commentnewsid').val();
                    $.ajax({
                        url: `${host}/comment/data`,
                        type: 'post',
                        data: formData
                    }).then(res => {
                        $('#addcomment').dialog('close');
                        $('#dgcomment').datagrid('reload');
                    })
                }
            }
        });
    }
    function clearForm() {
        $('#ff').form('clear');
    }

    //删除当前记录
    function deleData(id) {
        $.messager.confirm('删除确认框', '你确认要删除该记录码?', function (r) {
            if (r) {
                $.ajax({
                    url: `${host}/news/data/${id}`,
                    type: 'delete'
                }).then(res => {
                    $('#dg').datagrid('reload');
                    $.messager.show({
                        title: '提示',
                        msg: '已经成功删除记录.',
                        showType: 'show'
                    });
                })
            }
        });
    }

    //评论对话框
    function commentData(id,title){
        $('#dlgcomment').dialog('open');
        commentid=id
        $('#commentnewsid').val(id);
        $('#commentnews').val(title)
        $('.easyui-combobox').combobox({
            onSelect:function(node){
                if(node.value==1){
                    $('#checkData').hide();
                }else{
                    $('#checkData').show();
                }
                $('#dgcomment').datagrid({
                    url: `${host}/comment/list`,
                    pagination: true,
                    method: 'post',
                    queryParams:{
                        id : id,
                        type: node.value,
                    },
                    columns: [[
                        { field: 'ck', checkbox: true },
                        { field: 'news', title: '标题', width: 100,align:'center'},
                        { field: 'author', title: '评论者', width: 80,align:'center'},
                        { field: 'content', title: '内容', width: 150,align:'center' },
                        { field: 'time', title: '评论时间', width: 150,align:'center',
                            formatter:function(value,row,index){
                            return moment(value).format('YYYY-MM-DD');
                        } },
                        { field: 'state',title : '审核状态',width:60,align:'center'}
                    ]],
                    toolbar: '#tbcomment'
                });
            }
         })
    }

    //修改评论数
    function modifyCommentNum(){
        $.ajax({
            url: `${host}/comment/list`,
            type: 'post',
            data: {
                id:commentid
            }
        }).then(res=>{
            var commentArray=res.rows
            var passnum=0;
            $.each(commentArray,function(index,value){
                if(value.state=='通过'){
                    passnum++
                }
            })
            console.log(passnum)
            $.ajax({
                url: `${host}/news/data/${commentid}`,
                type: 'put',
                data: {
                    commentnum:passnum
                }
            }).then(res => {
                $('#dg').datagrid('reload');
            })
        })
    }

    //评论通过按钮
   
    $('#addcommentData').click(function(){
        $('#addcomment').dialog('open');
        $('#ffcomment').form('clear');
    })
    $('#checkData').on('click',function(){
        var checkselections = $('#dgcomment').datagrid('getSelections');
        var ids = [];
        for (let i = 0; i < checkselections.length; i++) {
            ids.push(checkselections[i]._id);
        };
        $.messager.confirm('审核确认框', '你确认要审核该记录码?', function (r) {
            if (r) {
                $.ajax({
                    url: `${host}/comment/data/updates`,
                    type: 'post',
                    data: {
                        ids: ids.toString()
                    }
                }).then(res => {
                    $('#dgcomment').datagrid('reload');
                    //---------------------------------------------------------
                    modifyCommentNum()
                    //---------------------------------------------------------
                    $.messager.show({
                        title: '提示',
                        msg: '已经成功审核记录.',
                        showType: 'show'
                    });
                })
            }
        });
    });
       
    //评论不通过按钮
    $('#uncheckData').on('click',function(){
        var checkselections = $('#dgcomment').datagrid('getSelections');
        var ids = [];
        for (let i = 0; i < checkselections.length; i++) {
            ids.push(checkselections[i]._id);
        };
        $.messager.confirm('审核确认框', '你确认要审核该记录码?', function (r) {
            if (r) {
                $.ajax({
                    url: `${host}/comment/data/unupdates`,
                    type: 'post',
                    data: {
                        ids: ids.toString()
                    }
                }).then(res => {
                    $('#dgcomment').datagrid('reload');
                    //----------------------------------------------------------
                    modifyCommentNum()
                    //------------------------------------------------------------
                })
            }
        });
    });

    //评论删除按钮
    $('#betchData').on('click',function(){
        var checkselections = $('#dgcomment').datagrid('getSelections');
        var ids = [];
        for (let i = 0; i < checkselections.length; i++) {
            ids.push(checkselections[i]._id);
        };
        $.messager.confirm('删除确认框', '你确认要删除记录码?', function (r) {
            if (r) {
                $.ajax({
                    url: `${host}/comment/data/removes`,
                    type: 'post',
                    data: {
                        ids: ids.toString()
                    }
                }).then(res => {
                    $('#dgcomment').datagrid('reload');
                    //------------------------------------------------------------
                    modifyCommentNum()
                    //-------------------------------------------------------------
                })
            }
        });
    });

    //修改记录
    function editData(id) {
        $('#ff').form('clear');
        $.ajax({
            url: `${host}/news/data/${id}`,
            type: 'get'
        }).then(res => {
            $('#ff').form('load', res);
            $('#dlg').dialog('open');
        })
    }
    
    
    $("#addData").click(function () {
        $('#ff').form('clear');
        $('#dlg').dialog('open')
    })

    //搜索记录
    $("#searchData").click(function () {
        $('#dg').datagrid({
            url: `${host}/news/list`,
            method: 'post',
            queryParams: {
                title: $("#searchName").val()
            }
        });
    })

    //移除多条记录
    $("#removesData").click(function () {
        var dgSelections = $('#dg').datagrid('getSelections');
        var ids = [];
        for (let i = 0; i < dgSelections.length; i++) {
            ids.push(dgSelections[i]._id);
        }
        $.messager.confirm('删除确认框', '你确认要删除该记录码?', function (r) {
            if (r) {
                $.ajax({
                    url: `${host}/news/data/removes`,
                    type: 'post',
                    data: {
                        ids: ids.toString()
                    }
                }).then(res => {
                    $('#dg').datagrid('reload');
                    $.messager.show({
                        title: '提示',
                        msg: '已经成功删除记录.',
                        showType: 'show'
                    });
                })
            }
        });

    })
    //删除节点
    $('#BtnDeleteNode').on('click',function(){
        deleteNode(nodeChecked)
    })
    function deleteNode(node){
        console.log(node)
        $.messager.confirm('删除确认框', '该操作将删除包含的所有数据，你确认要删除该节点码?', function (r) {
            if (r) {
                $.ajax({
                    
                    url: `${host}/cate/data/${node._id}`,
                    type: 'delete'
                }).then(res => {
                    $('#tt').tree('remove',nodeChecked.target)
                    $.ajax({
                        url: `${host}/news/data/nodeRemove`,
                        type: 'post',
                        data: {
                            id:node._id
                        }
                    }).then(res => {
                        $('#dg').datagrid('reload');
                        $.messager.show({
                            title: '提示',
                            msg: '已经成功删除记录.',
                            showType: 'show'
                        });
                    })
                })
            }
        });
    }

    //节点编辑
    $('#BtnEditNode').on('click',function(){
        editNode(nodeChecked)
    })
    function editNode(node){
        $('#tt').tree('beginEdit',node.target)
    }

    //添加子节点
    var newNode;
    var newNodeParent;
    $('#BtnAddNode').on('click',function(){
        addNode(nodeChecked)
    })
    function addNode(node){
        var selected = node
        $('#tt').tree('append', {
            parent: selected.target,
            data: [{
                type: selected.type,
                text: '请进行修改',
                parentId:selected._id
            }]
        })
        var nodeChildren=$('#tt').tree('getChildren',selected.target)
        newNode=nodeChildren[nodeChildren.length-1]
        $('#tt').tree('beginEdit',newNode.target)
        beforeEditText=newNode.text
        newNodeParent=$('#tt').tree('getParent',newNode.target)
    }
    
    //获取一级子节点
    function getLeafChildren(parentnoot){
        var leafNodes = [];
        $(parentnoot.target).next().children().children("div.tree-node").each(function(){   
            leafNodes.push($('#tt').tree('getNode',this));
        });
        return leafNodes;
    }
    //添加同级节点
    $('#BtnAddBroNode').on('click',function(){
        addBroNode(nodeChecked)
    })
    function addBroNode(node){
        var selected = node
        var nodeindex
        if($('#tt').tree('getParent',selected.target)){//非根节点
            newNodeParent=$('#tt').tree('getParent',selected.target)
            var brothers=getLeafChildren(newNodeParent)
            console.log(newNodeParent._id)
            console.log(brothers)
            $.each(brothers,function(index,value){
                if(value._id==selected._id){
                    nodeindex=index
                }
            })
            $('#tt').tree('insert', {
                after: selected.target,
                data: {
                    type:1,
                    text:'请进行修改',
                    parentId:newNodeParent._id
                }
            })
            brothers=getLeafChildren(newNodeParent)
            console.log(brothers)
            newNode=brothers[++nodeindex]
            console.log(newNode)
        }else{//根节点
            var roots=$('#tt').tree('getRoots')
            $.each(roots,function(index,value){
                if(value._id==selected._id){
                    nodeindex=index
                }
            })
            $('#tt').tree('insert', {
                after: selected.target,
                data: {
                    type:1,
                    text:'请进行修改'
                }
            })
            roots=$('#tt').tree('getRoots')
            newNode=roots[++nodeindex]
        }
        $('#tt').tree('beginEdit',newNode.target)
        beforeEditText=newNode.text
    }

    $('#tt').tree({
        url: `${host}/newscate/list`,
        method: 'get',
        //树节点左键点击
        onClick: function(node){
            $('#addData').linkbutton('enable');
            $('#searchData').linkbutton('enable');
            nodeSelected = $('#tt').tree('getSelected')
            nodeParent=$('#tt').tree('getParent',nodeSelected.target)
            $('#dg').datagrid({
                url: `${host}/news/list`,
                pagination:true,
                method: 'post',
                queryParams: {
                    belong: node._id
                },
                columns: [[
                    { field: 'ck', checkbox: true },
                    { field: 'title', title: '标题', width: 80 },
                    { field: 'subtitle', title: '副标题', width: 80 },
                    { field: 'content', title: '内容', width: 135 },
                    { field: 'parentcate', title: '上级分类', width: 70 },
                    { field: 'nowcate', title: '当前分类', width: 70 },
                    { field: 'pushtime', title: '上传时间', width: 80,formatter:function(value,row,index){
                        return moment(value).format('YYYY-MM-DD');
                    } },
                    { field: 'author', title: '作者', width: 50 },
                    { field: 'reporter', title: '记者', width: 50 },
                    { field: 'source', title: '来源', width: 50 },
                    { field: 'keyword', title: '关键字', width: 50 },
                    { field: 'commentnum', title: '评论数', width: 50 },
                    {
                        field: '_id', title: '用户操作', width:140,
                        formatter: function (value, row, index) {
                            return `<a href="javascript:editData('${row._id}')">修改</a> <a href="javascript:deleData('${row._id}')">删除</a> <a href="javascript:commentData('${row._id}','${row.title}')">查看评论</a>`;
                        }
                    }
                ]],
                toolbar: '#tb'
            });
        },
        //树节点右键菜单
        onContextMenu: function(e, node){ //给结点添加右键菜单 
            //console.log(node)
            nodeChecked = node
            //nodeCheckedParent=$('#tt').tree('getParent',nodeChecked.target)
            $(this).tree('select',nodeChecked.target)
            e.preventDefault();  //阻止右键默认事件
            $('#nodeMenu').menu('show', {  
                left: e.pageX,  
                top: e.pageY  
            }); 
        },
        onBeforeEdit:function(){
            beforeEditText=nodeChecked.text
        },
        onAfterEdit:function(node){
            if(beforeEditText=='请进行修改'){
                var data;
                if(newNodeParent){
                    data={
                        text:newNode.text,
                        type:newNode.type,
                        parentId:newNodeParent._id
                    }
                }else{
                    data={
                        text:newNode.text,
                        type:newNode.type
                    }
                }
                $.ajax({
                    url: `${host}/cate/data`,
                    type: 'post',
                    data: data
                }).then(function(){
                    $('#tt').tree('reload')
                })
            }else{
                $.ajax({
                    url: `${host}/cate/data/${nodeChecked._id}`,
                    type: 'put',
                    data: {
                        text:nodeChecked.text
                    }
                })
            }
            newNode=null;
            newNodeParent=null;
        } 
    });
</script>